<?php
// +----------------------------------------------------------------------
// | Genadmin [ Genadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\logic\system;

use app\basic\BaseLogic;
use exception\ApiException;
use app\admin\model\system\SystemConfig;
use app\admin\model\system\SystemConfigGroup;
use support\utils\Cache;
use support\utils\Helper;

/**
 * 参数配置逻辑层
 */
class SystemConfigLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new SystemConfig();
    }

    /**
     * 获取单项配置
     */
    public function getConfig($config)
    {
        $prefix = 'config_';
        $data = Cache::get($prefix . $config);
        if ($data) {
            return $data;
        }
        $info = $this->model->where('key', $config)->findOrEmpty();
        if ($info->isEmpty()) {
            throw new ApiException('配置项不存在');
        }
        Cache::set($prefix . $config, $info->toArray());
        return $info;
    }

    /**
     * 获取配置组
     */
    public function getGroup($config)
    {
        $prefix = 'cfg_';
        $data = Cache::get($prefix . $config);
        if ($data) {
            return $data;
        }
        $group = SystemConfigGroup::where('code', $config)->findOrEmpty();
        if ($group->isEmpty()) {
            throw new ApiException('配置组不存在');
        }
        $info = $this->model->where('group_id', $group->id)->select();
        Cache::set($prefix . $config, $info->toArray());
        return $info->toArray();
    }

    /*
     * 处理存储配置信息
     */
    public function getStrongConfig($storage)
    {
         $storage = array_values($storage);
         foreach ($storage as $key => $value){
            // 将关联数组变成有序数组
            // 将 $value 拆出来 和 status  一个级别
            if (isset($value['config']) && is_array($value['config'])) {
                // 直接合并数组
                $storage[$key] = array_merge($value, $value['config']);
                unset($storage[$key]['config']);
            }
        }
        return $storage;
    }


    /**
     * 根据分组ID获取配置
     * @param int $groupId $config
     * @return array
     */
    public function getConfigByGroup($config): array
    {
        $group_info = $this->getGroup($config);
        // 将数组组成 以为 key,value 关联数组
        return array_column($group_info, 'value', 'key');
    }
}
